/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.libarae.client.threads;

import java.net.SocketTimeoutException;
import javax.swing.JOptionPane;
import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Book;
import org.libarae.communication.request.IsbnLookUpRequest;
import org.libarae.communication.response.IsbnLookUpResponse;
import org.libarae.communication.response.Response;

/**
 *
 * @author Ben
 */
public class IsbnLookUpThread extends Thread{
    
    private String mISBN;
    private HasIsbnLookUpThread mParent;

    public IsbnLookUpThread(String mISBN, HasIsbnLookUpThread mParent)
    {
        this.mISBN = mISBN;
        this.mParent = mParent;
    }

    public void run()
    {
        // Create new Request.
        IsbnLookUpRequest r = new IsbnLookUpRequest();

        // Set the proper values in the ISBN.
        r.setIsbn(mISBN);

        Response response = null;

        // Send the Request off to the server.
        try
        {
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if(response == null)
        {
            System.err.println("Error sending to or recieveing from server");
        }

        // Got back a good response, so get the Book from the response and display it in the parent.
        if(response.getStatus() == Response.STATUS_GOOD)
        {
            IsbnLookUpResponse ilur = (IsbnLookUpResponse)response;

            Book b = ilur.getBook();

            mParent.displayBook(b);
        }

        //TODO: Handle error.
    }
}
